package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.common.R;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("新增用户")
    @PostMapping("/save")
    public R save(@RequestBody User user){
        //对密码加密
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        userService.save(user);
        log.info(String.valueOf(user));
        return R.success("新增成功");
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public R login(@RequestBody User user){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(queryWrapper);
        //如果没有找到
        if (one==null){
            return R.error("输入账号或密码错误");
        }else{
            //对传进来的密码进行加密
            String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            //如果加密和的密码与数据库不一致
            if (!password.equals(one.getPassword())){
                return R.error("输入账号或密码错误");
            }
        }

        String userId = String.valueOf(one.getId());

        //准备存放在IWT中的自定义数据
        Map<String, Object> info = new HashMap<>();
//        BeanUtils.copyProperties(one,info);
//        info.put("id",one.getId());
//        info.put("username", one.getUsername());
//        info.put("password", one.getPassword());


        //生成JWT字符串
        String token = JwtUtil.sign(userId,info);

        return R.success("token:" + token);
    }


}
